
--192.168.0.5 ip地址，如果不需要真机调试，可以写127.0.0.1
--10240 调试用的端口号，和debugger.lua文件中用的一样就可以
--"luasoar"一个字符串
--nil（不用理他）
--"win"关系到路径的处理，mac上使用"unix",windows使用"win"
--"E:/projects/android/mytest" 项目绝对路径。

local LuaDebugEnable = false

if LuaDebugEnable then
    local projectPath = ""
    local platformStr = ""
    local platform = cc.Application:getInstance():getTargetPlatform()
    if 2 == platform then --mac
        projectPath = string.match(cc.getAppPath(), "(.*)/.*/.*/.*")
        platformStr = "unix"
    elseif 0 == platform then --TODO need test
        projectPath = string.match(cc.getAppPath(), "(.*)/.*/.*/.*")
        platformStr = "win"
    end
    --print(platform,projectPath,platformStr)
    require("debugger")("127.0.0.1",10240,"luasoar",nil,platformStr,projectPath)
end


--local lmprof = require"lmprof"
--lmprof.start(cc.FileUtils:getInstance():getWritablePath().."lmprof.lua")
if custom.NodePool then
    custom.NodePool:destroyInstance()
end

local Director = cc.Director:getInstance()


--local ActionManager = Director:getActionManager()
--local ActionManagerEx = ccs.ActionManagerEx:getInstance()
local FileUtils = cc.FileUtils:getInstance()

--兼容性处理
if not FileUtils.writeDataToFile then
    FileUtils.writeDataToFile = function(self,content,path,cb)
        io.writefile(path,content,'w+b')
        if cb then
            cb(true)
        end
    end
end

if not FileUtils.writeStringToFile then
     FileUtils.writeStringToFile = function(self,content,path,cb)
        io.writefile(path,content,'w+')
        if cb then
            cb(true)
        end
    end
end

local storePath = cc.GetStorePath().."/assets/"
local UserDefault = cc.UserDefault:getInstance()
local lang = UserDefault:getStringForKey("LANGUAGE","")
if lang == "" then
    lang =  cc.Configuration:getInstance():getValue('LANGUAGE')
end
local searchPaths = {
    storePath.."assets.multilanguage/"..lang.."/src/?.lua",
    storePath.."assets.multilanguage/"..lang.."/res/?.lua",
    storePath.."src/?.lua",
    storePath.."res/?.lua",
    "assets.multilanguage/"..lang.."/src/?.lua",
    "assets.multilanguage/"..lang.."/res/?.lua",
    "src/?.lua",
    "res/?.lua",
}
package.path = table.concat(searchPaths,";")..package.path

for name,_ in pairs(package.loaded) do
    local pos = name:find("app%.") or name:find("scripts%.") or name:find("quick%.")
    if  pos and pos==1 then
        package.loaded[name]=nil
        -- print("package.loaded removed",name)
    else
        -- print("package.loaded not remove",name)
    end
end
package.loaded["protobuf"]=nil

FileUtils:setPopupNotify(false)


ErrorLogs = {}
cc.Configuration:getInstance()

local STP = require "StackTracePlus"

if cc.Configuration then
    NATIVE_DEBUG = cc.Configuration:getInstance():getValue('cocos2d.x.build_type') == 'DEBUG'
end


function __G__TRACKBACK__(errorMessage)
    local message = tostring(errorMessage)
    local tracemsg,tmpMessage,showFilePath = STP.stacktrace("", 2)
    --将[]中的字符串替换成 showFilePath

    local tmpIdx = string.find(message,"]")
    if tmpIdx and showFilePath then
        message = string.sub (message, tmpIdx)
        --showFilePath最好判断一下长度 可以截取最后的60个字符
        message = string.format("[%s%s",showFilePath,message)
    end

    if not ErrorLogs[message] then
        
        release_print("----------------------------------------")
        release_print("LUA ERROR: " .. message .. "\n")
        release_print(tracemsg)
        release_print("----------------------------------------")

        ErrorLogs[message] = true
        local CrashReportAPI = require("app.public.crashreport.CrashReportAPI")
        if CrashReportAPI then
            CrashReportAPI.reportException(message,tracemsg)
        end

        if NATIVE_DEBUG and custom.Utils.showMessageBox then
            local errMes = message .. "\n"..tracemsg
            custom.Utils:showMessageBox('LUA ERROR', errMes)
        end
    end
end

local function parseCommandLine()
    if NATIVE_DEBUG then
        if custom.Utils.getCommandLineParam then
            local commands = custom.Utils:getCommandLineParam()
            for _, v in ipairs(commands) do
                if v == '-develop' then
                    DEVELOP_MODEL = true
                    package.path = package.path .. ';dev/?.lua'
                    require 'develop'
                end
            end
        end
    end
end


--[[
app=nil
UIHandler=nil
ZD=nil
GD=nil
UD=nil
ACM=nil
EM=nil
FieldManager=nil
AM=nil
Constant=nil
Enums=nil
TeamManager = nil
FieldManager = nil
MapManager = nil
Res = nil
St = nil
Util = nil
]]

cc.isDead = function(obj)
    if type(obj)=="nil" then
        return true
    elseif type(obj)=="userdata" then
        return tolua.isnull(obj)
    else
        return false
    end
end

cc.isAlive = function(obj)
    if type(obj)=="nil" then
        return false
    elseif type(obj)=="userdata" then
        return not tolua.isnull(obj)
    else
        return true
    end
end


local chunksFile = "src/scripts.zip"
if FileUtils:isFileExist(chunksFile) then
    cc.LuaLoadChunksFromZIP(chunksFile)
end

local function main()
    release_print("main.lua init")

    require("config")
    require("cocos.init")
    require("quick.init")
    require("quick.shortcodes")
    require("quick.cc.init")

    require "app.utils.init"
    require "app.configs.init"

    -- collectgarbage("setpause", 100)
    -- collectgarbage("setstepmul", 5000)
    parseCommandLine()

    local platform = cc.Application:getInstance():getTargetPlatform()
    if platform == cc.PLATFORM_OS_WINDOWS or platform == cc.PLATFORM_OS_MAC then
        local scene = Director:getRunningScene()
        if not scene:getChildByName("leftMask") and display.safe_x > 0 then
            local gap = display.safe_x
            local leftStartColor = cc.c4b(0, 0, 0, 200)
            local leftEndColor = cc.c4b(0, 0, 0, 0)
            local rightStartColor = cc.c4b(0, 0, 0, 200)
            local rightEndColor = cc.c4b(0, 0, 0, 0)
            local leftPos = cc.p(1, 0)
            local rightPos = cc.p(-1, 0)
            local leftMask = cc.LayerGradient:create(leftStartColor, leftEndColor, leftPos)
            leftMask:ignoreAnchorPointForPosition(false)
            leftMask:setAnchorPoint(cc.p(0,0))
            leftMask:setPosition(0, 0)
            leftMask:setContentSize(cc.size(gap, display.height))
            leftMask:setName("leftMask")
            scene:addChild(leftMask, 1000000)

            local rightMask = cc.LayerGradient:create(rightStartColor, rightEndColor, rightPos)
            rightMask:ignoreAnchorPointForPosition(false)
            rightMask:setAnchorPoint(cc.p(1,0))
            rightMask:setPosition(display.width, 0)
            rightMask:setContentSize(cc.size(gap, display.height))
            rightMask:setName("rightMask")
            scene:addChild(rightMask, 1000000)
        end
    end

    require("app.GameApp").new()
    require("app.loading.init")

    app:sendMsg("LoadingController", "gameInitLoading")
end
--cc.PrintLeaks()

xpcall(main, __G__TRACKBACK__)

print("======>Lua Memory ",collectgarbage("count"),"KB")